const path = require('path');

const Multer = require('koa-multer');
const Jimp = require('jimp');
const circlePlugin = require('@jimp/plugin-circle');

const {AVATAR_PATH, PICTURE_PATH} = require('../constants/file-path');

const avatarUpload = Multer({
  dest: AVATAR_PATH
});
const avatarHandler = avatarUpload.single('avatar');

const pictureUpload = Multer({
  dest: PICTURE_PATH
});
const pictureHandler = pictureUpload.array('picture', 9);

const pictureResize = async (ctx, next) => {
  try {
    // 1.获取所有的图像信息
    const files = ctx.req.files;

    // 2.对图像进行处理(sharp/jimp)
    for (let file of files) {
      const destPath = path.join(file.destination, file.filename);
      console.log(destPath);
      Jimp.read(file.path).then(image => {
        image.resize(1280, Jimp.AUTO).write(`${destPath}-large`);
        image.resize(640, Jimp.AUTO).write(`${destPath}-middle`);
        image.resize(320, Jimp.AUTO).write(`${destPath}-small`);
      });
    }

    await next();
  } catch (error) {
    console.log(error);
  }
}

const pictureComposite = async (ctx, next) => {
  console.log("image.circle", Jimp.circle, circlePlugin, circlePlugin.circle)
  const {name, position} = ctx.query;
  console.log("name", name, "position", position)
  const idPhotoPath = './imgs/id.png'
  const idPhotoWidth = 510; // 根据实际需求调整宽度
  const idPhotoHeight = 318; // 根据实际需求调整高度
  // const idPhoto = Jimp.read(idPhotoPath)
  // 调整用户照片的大小以适应证件照
  const userPhotoWidth = 125; // 根据实际需求调整宽度
  const userPhotoHeight = 165; // 根据实际需求调整高度

  try {
    // 1.获取所有的图像信息
    const files = ctx.req.files;
    // 2.对图像进行处理(sharp/jimp)
    for (let file of files) {
      const destPath = path.join(file.destination, file.filename);
      // Jimp.read(idPhotoPath)
      //   .then(async (idPhoto) => {
      //     idPhoto.resize(idPhotoWidth, idPhotoHeight)
      //     return Jimp.read(file.path)
      //       .then(async (userPhoto) => {
      //         userPhoto.resize(userPhotoWidth, userPhotoHeight);
      //         // userPhoto = await generateEllipse('#FF0000', userPhotoWidth, userPhotoHeight, userPhoto, destPath)
      //
      //
      //         // 计算用户照片的位置
      //         const userPhotoX = 33; // 根据实际需求调整 X 坐标
      //         const userPhotoY = 86; // 根据实际需求调整 Y 坐标
      //         idPhoto.composite(userPhoto, userPhotoX, userPhotoY)
      //         // 为合成的图像添加文字
      //         const fontX = 310; // 根据实际需求调整 X 坐标
      //         const fontY = 105; // 根据实际需求调整 Y 坐标
      //         const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
      //         idPhoto.print(font, fontX, fontY, name);
      //         const positionFontX = 310; // 根据实际需求调整 X 坐标
      //         const positionFontY = 205; // 根据实际需求调整 Y 坐标
      //         const positionFont = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
      //         idPhoto.print(positionFont, positionFontX, positionFontY, position);
      //         // 保存合成后的图像
      //         idPhoto.write(`${destPath}-middle`);
      //         console.log('图片合成成功！');
      //         await next();
      //       });
      //   })
      //   .catch(err => {
      //     console.error('图像处理过程中出现错误：', err);
      //   });
      const idPhotoPathRes = await Jimp.read(idPhotoPath)
      idPhotoPathRes.resize(idPhotoWidth, idPhotoHeight)
      const userPhoto = await Jimp.read(file.path)
      userPhoto.resize(userPhotoWidth, userPhotoHeight);
      // userPhoto = await generateEllipse('#FF0000', userPhotoWidth, userPhotoHeight, userPhoto, destPath)
      const userPhotoRes = await Jimp.read(file.path)
      userPhotoRes.resize(userPhotoWidth, userPhotoHeight);
      // 计算用户照片的位置
      const userPhotoX = 33; // 根据实际需求调整 X 坐标
      const userPhotoY = 86; // 根据实际需求调整 Y 坐标
      idPhotoPathRes.composite(userPhotoRes, userPhotoX, userPhotoY)
      // 为合成的图像添加文字
      const fontX = 310; // 根据实际需求调整 X 坐标
      const fontY = 105; // 根据实际需求调整 Y 坐标
      const font = await Jimp.loadFont('./imgs/font/PingFang_24_BLACK.fnt');
      idPhotoPathRes.print(font, fontX, fontY, name);
      const positionFontX = 310; // 根据实际需求调整 X 坐标
      const positionFontY = 205; // 根据实际需求调整 Y 坐标
      const positionFont = await Jimp.loadFont('./imgs/font/PingFang_24_BLACK.fnt');
      idPhotoPathRes.print(positionFont, positionFontX, positionFontY, position);
      // 保存合成后的图像
      idPhotoPathRes.write(`${destPath}-middle`);
      console.log('图片合成成功！');
      await next();
    }
    // await next();
  } catch (error) {
    console.log(error);
  }
}

async function handleUserPhoto(userPhoto) {

  const size = Math.min(userPhoto.getWidth(), userPhoto.getHeight());
  const diameter = size - 20; // 椭圆的直径
  const x = Math.floor((userPhoto.getWidth() - diameter) / 2);
  const y = Math.floor((userPhoto.getHeight() - diameter) / 2);

  // 创建一个新的椭圆图像
  const ellipseImage = await new Jimp(diameter, diameter, '#00000000');

  // 将原始图像裁剪为椭圆形状并复制到新的椭圆图像中
  userPhoto.circle({radius: diameter / 2, x: x, y: y}, (err, croppedImage) => {
    if (err) {
      console.error(err);
      return;
    }
    // croppedImage.mask(ellipseImage, 0, 0).write(outputFile);
    console.log('图片裁剪为椭圆形状成功！');
  })
}

async function generateEllipse(color, width, height, inputImage, destPath) {
  // 创建一个新的图像对象，用于存储输出图像
  const outputImage = await new Jimp(width, height);


  // 设置椭圆参数
  const centerX = Math.floor(width / 2);
  const centerY = Math.floor(height / 2);
  const radiusX = Math.floor(width / 2);
  const radiusY = Math.floor(height / 2);

  // 处理每个像素，只保留椭圆内部的像素
  outputImage.scan(0, 0, width, height, function (x, y, idx) {
    const dx = x - centerX;
    const dy = y - centerY;
    if ((dx * dx) / (radiusX * radiusX) + (dy * dy) / (radiusY * radiusY) <= 1) {
      // 在椭圆内部复制输入图像的像素
      const inputPixel = inputImage.getPixelColor(x, y);
      const {r, g, b, a} = Jimp.intToRGBA(inputPixel);
      this.bitmap.data[idx] = r;
      this.bitmap.data[idx + 1] = g;
      this.bitmap.data[idx + 2] = b;
      this.bitmap.data[idx + 3] = a;
    } else {
      // 在椭圆外部设置透明像素
      this.bitmap.data[idx] = 0;
      this.bitmap.data[idx + 1] = 0;
      this.bitmap.data[idx + 2] = 0;
      this.bitmap.data[idx + 3] = 0;
    }
  });

  // outputImage.write(`${destPath}-middle`);

  console.log('图像裁剪成功！');
  return outputImage
}

module.exports = {
  avatarHandler,
  pictureHandler,
  pictureResize,
  pictureComposite
}
